<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>时间类型的平移缩放</title>
  <link rel="stylesheet" href="./assets/common.css">
  <style>
  .chart-container {
    position: relative;
  }
  .chart-legend {
  height: 12vw;
  padding: 3.2vw;
  font-size: 3.2vw;
  color: #808080;
  display: flex;
  flex-wrap: wrap;
  align-content: space-between;
}

canvas {
  width: 100%;
  height: 60vw;
}

.chart-legend-title {
  display: none;
}

.item {
  width: 33%;
  margin: 1px 0;
}

.item span {
  display: inline;
}

.item span.item-marker {
  display: inline-block;
  width: 6px;
  height: 2px;
  margin-right: 2px;
  margin-top: -1px;
  border-radius: 3px;
  vertical-align: middle;
  opacity: 0.5;
}

.item span.item-marker-point {
  display: inline-block;
  width: 5px;
  height: 5px;
  margin-right: 2px;
  margin-top: -1px;
  border-radius: 50%;
  vertical-align: middle;
}

.item-value {
  color: #2E2E2E;
}

.tooltip-wrapper {
  position: absolute;
  visibility: hidden;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 16vw;
  background: #E9F1FF;
  padding: 3.2vw 3.2vw 0;
  z-index: 10;
  transition: visibility 0.2s cubic-bezier(0.23, 1, 0.32, 1);
}

.tooltip-title {
  font-size: 3.2vw;
  line-height: 4vw;
  height: 4vw;
  color: #2e2e2e;
  margin-bottom: 8px;
}

.tooltip-content {
  font-size: 3.2vw;
  color: #808080;
  display: flex;
  flex-wrap: wrap;
  align-content: space-between;
}



  </style>
</head>
<body>
      <div class="chart-container">
        <div class="tooltip-wrapper">
          <div class="tooltip-title" id="tooltipTitle"></div>
          <div class="tooltip-content" id="tooltip">
            <div class="item">
              <span class="item-marker" style="background: #1890ff"></span>
              <span>本基金:</span>
              <span class="item-value" data-type="本基金">--</span>
            </div>
            <div class="item">
              <span class="item-marker" style="background: #5CDBD3"></span>
              <span>同类均值:</span>
              <span class="item-value" data-type="同类平均">--</span>
            </div>
            <div class="item" style="padding-right: 0;">
              <span class="item-marker" style="background: #B37FEB"></span>
              <span>沪深300:</span>
              <span class="item-value" data-type="沪深300">--</span>
            </div>
          </div>
        </div>
        <!-- 自定义 html 图表图例 -->
        <div class="chart-legend" id="chartLegend">
          <div class="chart-legend-title"></div>
          <div class="item">
            <span class="item-marker" style="background: #1890ff"></span>
            <span>本基金:</span>
            <span class="item-value" data-type="本基金">--</span>
          </div>
          <div class="item">
            <span class="item-marker" style="background: #5CDBD3"></span>
            <span>同类均值:</span>
            <span class="item-value" data-type="同类平均">--</span>
          </div>
          <div class="item" style="padding-right: 0;">
            <span class="item-marker" style="background: #B37FEB"></span>
            <span>沪深300:</span>
            <span class="item-value" data-type="沪深300">--</span>
          </div>
        </div>
        <!-- 图表主题 -->
        <canvas id="mountNode"></canvas>
      </div>
<script src="./assets/jquery-3.2.1.min.js"></script>
<script src="../build/f2-all.js"></script>
<script src="https://gw.alipayobjects.com/os/rmsportal/NjNldKHIVQRozfbAOJUW.js"></script>
<script>
  var Animate = F2.Animate;
    var Util = F2.Util;
    var Chart = F2.Chart;
    // 自定义线图变更动画
    Animate.registerAnimation('lineUpdate', function (updateShape, animateCfg) {
      var cacheShape = updateShape.get('cacheShape'); // 该动画 shape 的前一个状态
      var cacheAttrs = cacheShape.attrs; // 上一个 shape 属性

      var oldPoints = cacheAttrs.points; // 上一个状态的关键点
      var newPoints = updateShape.attr('points'); // 当前 shape 的关键点

      var oldLength = oldPoints.length;
      var newLength = newPoints.length;
      var deltaLength = oldLength - newLength;

      if (deltaLength > 0) {
        var firstPoint = newPoints[0];
        var lastPoint = newPoints[newPoints.length - 1];

        for (var i = 0; i < deltaLength; i++) {
          newPoints.splice(0, 0, firstPoint);
        }
      } else {
        deltaLength = Math.abs(deltaLength);
        var firstPoint1 = oldPoints[0];
        var lastPoint1 = oldPoints[oldPoints.length - 1];

        for (var k = 0; k < deltaLength; k++) {
          oldPoints.splice(0, 0, firstPoint1);
        }
        cacheAttrs.points = oldPoints;
      }
      updateShape.attr(cacheAttrs);
      updateShape.animate().to(Util.mix({
        attrs: {
          points: newPoints
        }
      }, animateCfg));
    });
  var colorMap = {
      '本基金': '#1890FF',
      '沪深300': 'rgba(92, 219, 211, 0.5)',
      '同类平均': 'rgba(179, 127, 235, 0.5)'
    };
    var sizeMap = {
      '本基金': 2,
      '沪深300': 1,
      '同类平均': 1
    };

    // 昨天的收益率，用于图例的绘制，无论时间切换维度多少，默认都会显示昨天的收益率
    var yesterdayRates = {
      '本基金': 14.12,
      '沪深300': 3.71,
      '同类平均': 3.54
    };
    var yesterday = '2018-05-22（昨日）';

    // 图表绘制完成之后绘制图例
    $('#chartLegend .chart-legend-title').text(yesterday);
    $('#chartLegend .item-value').each(function (index, ele) {
      var type = $(ele).data('type');
      var value = yesterdayRates[type];
      var color;
      if (value > 0) {
        value = '+' + value;
        color = '#F5222D';
      }
      if (value < 0) {
        color = '#53BC20';
      }
      $(ele).css({
        color: color
      });
      $(ele).text(value + '%');
    });

    // 处理数据
    $.getJSON('./data/performance-three-year.json', function (json) {
      const dates = [];
      json.forEach(obj => {
        dates.push(obj.reportDate);
      });
      var chart = new F2.Chart({
        id: 'mountNode',
        pixelRatio: window.devicePixelRatio,
        padding: [14, 'auto', 'auto']
      });
      chart.source(json, {
        reportDate: {
          type: 'timeCat',
          tickCount: 3,
          range: [0, 1],
          mask: 'YYYY-MM-DD',
          values: dates.slice(0, 50)
        },
        rate: {
          tickCount: 5
        },
        name: {
          values: ['沪深300', '同类平均', '本基金']
        }
      });
      chart.axis('reportDate', {
        line: null,
        label: function (text, index, total) {
          var cfg = {
            textAlign: 'center'
          };
          if (index === 0) {
            cfg.textAlign = 'start';
          } else if (index === (total - 1)) {
            cfg.textAlign = 'end';
          }

          var arr = text.split('-');
          if (arr[0] === '2018') {
            cfg.text = arr[1] + '-' + arr[2];
          }
          return cfg;
        }
      });
      chart.axis('rate', {
        label: function (text) {
          text = text * 1;
          var cfg = {
            text: text.toFixed(2) + '%'
          };
          if (text > 0) {
            cfg.text = '+' + cfg.text;
          } else if (text === 0) {
            cfg.fill = '#000';
            cfg.fontWeight = 'bold';
          }
          return cfg;
        },
        grid: function (text, index) {
          if (text == 0) {
            return {
              lineDash: null
            };
          }
        }
      });
      chart.legend(false); // 不使用默认图例
      chart.tooltip({
        crosshairsStyle: {
          stroke: '#CAD7EF'
        },
        custom: true,
        onChange: function (obj) {
          var items = obj.items;
          var title = items[0].origin.reportDate;

          var rates = {};
          items.forEach(function (item) {
            rates[item.name] = item.value * 1;
          });
          $('#tooltipTitle').text(title);
          $('#tooltip .item-value').each(function (index, ele) {
            var type = $(ele).data('type');
            var value = rates[type];
            var color;
            if (value > 0) {
              value = '+' + value;
              color = '#F5222D';
            } else if (value < 0) {
              color = '#53BC20';
            } else {
              color = '#2E2E2E';
            }
            $(ele).css({
              color
            });
            $(ele).text(value + '%');
          });

          $('.tooltip-wrapper').css('visibility', 'visible');
        },
        onHide: function () {
          $('.tooltip-wrapper').css('visibility', 'hidden');
        }
      });
      chart.line()
        .position('reportDate*rate')
        .color('name', function (val) {
          return colorMap[val];
        })
        .size('name', function (val) {
          return sizeMap[val];
        })
        .animate({
          update: {
            duration: 1000
          }
        });
      chart.interaction('pan');
      chart.interaction('pinch');
      chart.interaction('swipe');

      // 添加进度条
      chart.scrollBar({
        mode: 'x',
        xStyle: {
          offsetY: -5
        }
      });
      chart.render();
    });
</script>
</body>
</html>
